# -*- coding: utf-8 -*-
"""UI主题管理模块"""

from tkinter import ttk


class ThemeManager:
    """管理应用程序的UI主题"""

    def __init__(self, root=None):
        """初始化主题管理器

        Args:
            root: 根窗口实例
        """
        self.root = root
        self.current_theme = "light"

        # 预定义的主题样式
        self.themes = {
            "light": {
                "background": "#f0f0f0",
                "foreground": "#000000",
                "button_bg": "#e0e0e0",
                "button_fg": "#000000",
                "frame_bg": "#e8e8e8",
                "entry_bg": "#ffffff",
                "entry_fg": "#000000",
                "header_bg": "#4a7abc",
                "header_fg": "#ffffff",
                "table_header_bg": "#d0d0d0",
                "table_alternate_bg": "#f5f5f5",
                "status_bar_bg": "#e0e0e0",
                "status_bar_fg": "#000000",
            },
            "dark": {
                "background": "#2d2d2d",
                "foreground": "#ffffff",
                "button_bg": "#4a4a4a",
                "button_fg": "#ffffff",
                "frame_bg": "#3a3a3a",
                "entry_bg": "#505050",
                "entry_fg": "#ffffff",
                "header_bg": "#355c8b",
                "header_fg": "#ffffff",
                "table_header_bg": "#505050",
                "table_alternate_bg": "#3a3a3a",
                "status_bar_bg": "#4a4a4a",
                "status_bar_fg": "#ffffff",
            },
            "high_contrast": {
                "background": "#ffffff",
                "foreground": "#000000",
                "button_bg": "#000000",
                "button_fg": "#ffffff",
                "frame_bg": "#e0e0e0",
                "entry_bg": "#ffffff",
                "entry_fg": "#000000",
                "header_bg": "#000000",
                "header_fg": "#ffffff",
                "table_header_bg": "#000000",
                "table_alternate_bg": "#f0f0f0",
                "status_bar_bg": "#e0e0e0",
                "status_bar_fg": "#000000",
            },
        }

        # 预定义的字体样式
        self.fonts = {
            "small": ("Microsoft YaHei", 9),
            "normal": ("Microsoft YaHei", 10),
            "large": ("Microsoft YaHei", 12),
            "extra_large": ("Microsoft YaHei", 14, "bold"),
            "header": ("Microsoft YaHei", 12, "bold"),
            "button": ("Microsoft YaHei", 10, "normal"),
            "status": ("Microsoft YaHei", 9, "normal"),
        }

    def set_theme(self, theme_name, apply=True):
        """设置应用程序的主题

        Args:
            theme_name: 主题名称，必须是预定义的主题之一
            apply: 是否立即应用主题
        """
        if theme_name in self.themes:
            self.current_theme = theme_name
            if apply and self.root:
                self.apply_theme()
            return True
        return False

    def apply_theme(self):
        """应用当前主题到根窗口及其所有子组件"""
        if not self.root or self.current_theme not in self.themes:
            return

        theme = self.themes[self.current_theme]

        # 设置根窗口的主题
        self.root.configure(bg=theme["background"])

        # 设置ttk样式
        style = ttk.Style(self.root)

        # 配置ttk主题基础样式
        style.configure("TFrame", background=theme["frame_bg"])

        style.configure(
            "TLabel",
            background=theme["background"],
            foreground=theme["foreground"],
            font=self.fonts["normal"],
        )

        style.configure(
            "TButton",
            background=theme["button_bg"],
            foreground=theme["button_fg"],
            font=self.fonts["button"],
        )

        style.configure(
            "TEntry",
            fieldbackground=theme["entry_bg"],
            foreground=theme["entry_fg"],
            font=self.fonts["normal"],
        )

        # 配置表格样式
        style.configure(
            "Treeview",
            background=theme["background"],
            foreground=theme["foreground"],
            fieldbackground=theme["background"],
            font=self.fonts["small"],
            rowheight=25,
        )

        style.configure(
            "Treeview.Heading",
            background=theme["table_header_bg"],
            foreground=theme["foreground"],
            font=self.fonts["normal"],
            padding=(5, 3),
        )

        # 设置表格交替行颜色
        style.map(
            "Treeview",
            background=[
                ("selected", theme["header_bg"]),
                ("alternate", theme["table_alternate_bg"]),
            ],
        )

        # 自定义样式
        style.configure(
            "Header.TLabel",
            background=theme["header_bg"],
            foreground=theme["header_fg"],
            font=self.fonts["header"],
            padding=(10, 5),
        )

        style.configure(
            "Status.TLabel",
            background=theme["status_bar_bg"],
            foreground=theme["status_bar_fg"],
            font=self.fonts["status"],
            padding=(5, 2),
        )

        style.configure(
            "Title.TLabel",
            font=self.fonts["extra_large"],
            foreground=theme["foreground"],
            background=theme["background"],
            padding=(10, 5),
        )

    def get_theme_colors(self):
        """获取当前主题的颜色配置

        Returns:
            dict: 包含当前主题所有颜色配置的字典
        """
        return self.themes.get(self.current_theme, self.themes["light"])

    def get_font(self, font_name):
        """获取指定名称的字体配置

        Args:
            font_name: 字体名称，必须是预定义的字体之一

        Returns:
            tuple: 字体配置 (font_family, font_size, font_style)
        """
        return self.fonts.get(font_name, self.fonts["normal"])

    def create_custom_style(self, style_name, base_style, **kwargs):
        """创建自定义样式

        Args:
            style_name: 自定义样式名称
            base_style: 基础样式名称
            **kwargs: 要覆盖的样式属性
        """
        if not self.root:
            return

        style = ttk.Style(self.root)
        style.configure(f"{style_name}.{base_style}", **kwargs)

    def apply_style_to_widget(self, widget, style_name):
        """应用样式到特定组件

        Args:
            widget: 要应用样式的组件
            style_name: 样式名称
        """
        if hasattr(widget, "configure"):
            if style_name in self.themes[self.current_theme]:
                widget.configure(
                    bg=self.themes[self.current_theme][style_name]
                )

    def get_available_themes(self):
        """获取所有可用的主题名称

        Returns:
            list: 可用主题名称列表
        """
        return list(self.themes.keys())

    def toggle_theme(self):
        """切换到下一个可用的主题"""
        themes = self.get_available_themes()
        current_index = themes.index(self.current_theme)
        next_index = (current_index + 1) % len(themes)
        self.set_theme(themes[next_index])
        return themes[next_index]
